aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(app)/ln/[lnurl]/+page.server.ts
blob: 7b63e6f53b1a9f02995b9ce83124c779851c0138 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import getRates from "$lib/rates";
import { auth, fd, get, post } from "$lib/utils";
import { error, fail, redirect } from "@sveltejs/kit";

export async function load({ params, parent }) {
	const { user } = await parent();
	if (!user) redirect(307, "/register");
	const rates = await getRates();

	let data;
	try {
		const { lnurl } = params;
		data = await get(`/decode?text=${lnurl}`);
	} catch (e) {
		const { message } = e as Error;
		error(500, message);
	}

	if (!["payRequest", "withdrawRequest"].includes(data.tag))
		error(500, "We only support LNURLp and LNURLw at this time");

	data.rate = rates[user.currency];
	return data;
}

export const actions = {
	pay: async ({ fetch, request }) => {
		let error;

		let { callback, amount, minSendable, maxSendable, comment } =
			await fd(request);
		minSendable = Math.round(minSendable / 1000);
		maxSendable = Math.round(maxSendable / 1000);

		if (amount < minSendable)
			error = `Amount must be at least ${minSendable} sats`;
		if (amount > maxSendable)
			error = `Amount must be at most ${maxSendable} sats`;
		if (error) return fail(400, { error });

		let url = `${callback}?amount=${amount * 1000}`;
		if (comment) url += `&comment=${comment}`;

		const { pr } = await fetch(url).then((r) => r.json());
		redirect(307, `/send/lightning/${pr}`);
	},

	withdraw: async ({ cookies, fetch, request }) => {
		let error;

		let {
			callback,
			amount,
			username,
			currency,
			minWithdrawable,
			maxWithdrawable,
			k1,
		} = await fd(request);

		minWithdrawable = Math.round(minWithdrawable / 1000);
		maxWithdrawable = Math.round(maxWithdrawable / 1000);

		if (amount < minWithdrawable)
			error = `Amount must be at least ${minWithdrawable} sats`;
		if (amount > maxWithdrawable)
			error = `Amount must be at most ${maxWithdrawable} sats`;
		if (error) return fail(400, { error });

		const invoice = { amount, type: "lightning" };
		const user = { username, currency };

		const { text: pr } = await post(
			"/invoice",
			{ invoice, user },
			auth(cookies),
		);

		const url = new URL(callback);
		url.searchParams.append("k1", k1);
		url.searchParams.append("pr", pr);

		await fetch(url.toString());

		redirect(307, "/payments");
	},
};